<template>
  <div class="development-view">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="view-card">
          <template #header>
            <div class="card-header">
              <span>员工能力评估与职业发展建议</span>
            </div>
          </template>

          <div class="development-content" id="dev-content">
            <!-- 评估控制区域 -->
            <div class="assessment-section">
              <h3>能力评估</h3>
              <el-form :model="developmentForm" label-width="120px">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="选择员工">
                      <el-select
                        v-model="developmentForm.employeeId"
                        placeholder="请选择员工"
                        filterable
                        @change="onEmployeeSelect"
                      >
                        <el-option
                          v-for="employee in employees"
                          :key="employee.id"
                          :label="employee.name"
                          :value="employee.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <!-- <el-col :span="8">
                    <el-form-item label="职业目标">
                      <el-select
                        v-model="developmentForm.careerGoal"
                        placeholder="请选择职业目标"
                      >
                        <el-option label="技术专家路径" value="technical" />
                        <el-option label="管理发展路径" value="management" />
                        <el-option label="项目管理路径" value="project" />
                        <el-option label="业务专家路径" value="business" />
                      </el-select>
                    </el-form-item>
                  </el-col> -->
                  <el-col :span="8">
                    <el-form-item>
                      <el-button
                        type="primary"
                        @click="generateDevelopmentPlan"
                        :loading="generating"
                        :disabled="!developmentForm.employeeId"
                      >
                        开始评估
                      </el-button>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>

            <el-tabs
              v-model="activeName"
              class="demo-tabs"
              @tab-click="handleClickTAB"
              v-if="selectedEmployee && developmentPlan"
            >
              <el-tab-pane label="员工综合能力评估" name="test">
                <!-- 员工能力概览 -->
                <div v-if="selectedEmployee" class="employee-overview">
                  <h3>员工能力概览</h3>
                  <el-row :gutter="20">
                    <el-col :span="8">
                      <el-card class="metric-card">
                        <div class="metric-content">
                          <div class="metric-value">
                            {{ averageTrainingScore }}
                          </div>
                          <div class="metric-label">平均培训成绩</div>
                        </div>
                      </el-card>
                    </el-col>
                    <el-col :span="8">
                      <el-card class="metric-card">
                        <div class="metric-content">
                          <div class="metric-value">
                            {{ averagePerformanceScore }}
                          </div>
                          <div class="metric-label">平均绩效评分</div>
                        </div>
                      </el-card>
                    </el-col>
                    <el-col :span="8">
                      <el-card class="metric-card">
                        <div class="metric-content">
                          <div class="metric-value">{{ workExperience }}</div>
                          <div class="metric-label">工作经验(年)</div>
                        </div>
                      </el-card>
                    </el-col>
                  </el-row>
                </div>
                <h3>个性化发展计划</h3>

                <!-- 能力雷达图 -->
                <div class="radar-chart-section">
                  <h4>能力维度分析</h4>
                  <div class="radar-chart-placeholder">
                    <!-- 这里可以集成echarts等图表库 -->
                    <!-- 雷达图容器，必须指定宽高 -->
                    <!-- <div id="main" style="height: 289px"></div> -->
                    <div
                      id="main"
                      style="width: 600px; height: 289px"
                      ref="mainEcgart"
                    ></div>
                  </div>
                </div>
              </el-tab-pane>

              <el-tab-pane label="职业发展建议" name="plan">
                <!-- 发展计划 -->
                <div v-if="developmentPlan" class="development-plan">
                  <!-- 发展建议 -->
                  <div class="suggestions-section">
                    <el-row :gutter="20">
                      <el-col :span="12">
                        <el-card class="suggestion-card">
                          <template #header>
                            <div class="suggestion-header">
                              <el-icon>
                                <Reading />
                              </el-icon>
                              <span>培训建议</span>
                            </div>
                          </template>
                          <ul class="suggestion-list">
                            <li
                              v-for="(
                                suggestion, index
                              ) in developmentPlan.trainingSuggestions"
                              :key="index"
                              class="suggestion-item"
                            >
                              {{ suggestion }}
                            </li>
                          </ul>
                        </el-card>
                      </el-col>
                      <el-col :span="12">
                        <el-card class="suggestion-card">
                          <template #header>
                            <div class="suggestion-header">
                              <el-icon>
                                <Promotion />
                              </el-icon>
                              <span>晋升路径</span>
                            </div>
                          </template>
                          <div class="promotion-path">
                            <div
                              v-for="(
                                step, index
                              ) in developmentPlan.promotionPath"
                              :key="index"
                              class="path-step"
                            >
                              <div class="step-number">{{ index + 1 }}</div>
                              <div class="step-content">
                                <div class="step-title">
                                  {{ step.position }}
                                </div>
                                <div class="step-duration">
                                  {{ step.duration }}
                                </div>
                                <div class="step-requirements">
                                  <el-tag
                                    v-for="req in step.requirements"
                                    :key="req"
                                    size="small"
                                    type="info"
                                  >
                                    {{ req }}
                                  </el-tag>
                                </div>
                              </div>
                            </div>
                          </div>
                        </el-card>
                      </el-col>
                    </el-row>
                  </div>

                  <!-- 行动计划 -->
                  <div class="action-plan-section">
                    <h4>详细行动计划</h4>
                    <el-timeline>
                      <el-timeline-item
                        v-for="(action, index) in developmentPlan.actionPlan"
                        :key="index"
                        :timestamp="action.timestamp"
                        :type="action.type"
                      >
                        {{ action.content }}
                      </el-timeline-item>
                    </el-timeline>
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>

            <!-- 无数据提示 -->
            <el-empty
              v-if="!selectedEmployee"
              description="请选择员工查看能力评估和发展建议"
              class="empty-state"
            />
          </div>
          <el-button
            type="primary"
            style="margin-top: 1rem; margin-left: 50rem"
            v-if="developmentPlan"
            @click="handleDownloadReport"
            >下载员工能力评估与职业发展建议报告</el-button
          >
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, onMounted, computed, onBeforeUnmount } from "vue";
import { ElMessage } from "element-plus";
import { Reading, Promotion } from "@element-plus/icons-vue";
import { useStore } from "vuex";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import * as echarts from "echarts";

import api from "@/services/api";

export default {
  name: "DevelopmentView",
  components: {
    Reading,
    Promotion,
  },
  setup() {
    const store = useStore();

    const developmentForm = ref({
      employeeId: "",
      careerGoal: "technical",
    });
    const selectedEmployee = ref(null);
    const developmentPlan = ref(null);
    const generating = ref(false);

    const sumScore = ref(76.1);
    const echartsDataArr = ref([40, 73, 85, 40, 100]);
    const mainEcgart = ref(null);
    let myChart = null;
    let isMounted = false; // 守卫变量：标记组件是否挂载
    let employeeIdNow = "";
    const activeName = ref("test");

    const employees = computed(() => store.state.employees);

    const averageTrainingScore = computed(() => {
      if (!selectedEmployee.value) return "0.0";
      // 这里应该从API获取实际的培训平均分
      return "8.5";
    });

    const averagePerformanceScore = computed(() => {
      if (!selectedEmployee.value) return "0.0";
      // 这里应该从API获取实际的绩效平均分
      return "4.2";
    });

    const workExperience = computed(() => {
      return selectedEmployee.value ? selectedEmployee.value.workYears : "0";
    });

    const loadData = async () => {
      try {
        await store.dispatch("loadEmployees");
      } catch (error) {
        ElMessage.error("数据加载失败");
      }
    };

    const onEmployeeSelect = async (employeeId) => {
      employeeIdNow = employeeId;
      try {
        const response = await api.getEmployeeData(employeeId);
        selectedEmployee.value = response.data.employee;
      } catch (error) {
        ElMessage.error("加载员工数据失败");
      }
      let name;
      employees.value.forEach((val) => {
        if (val.id == employeeId) {
          name = val.name;
        }
      });
      await api.searchEmployees(name);
    };

    const generateDevelopmentPlan = async () => {
      try {
        const resEmployees = await api.getEmployees();
        employees.value = resEmployees.data;
      } catch (error) {
        console.error("加载员工数据失败:", error);
      }
      if (!developmentForm.value.employeeId) {
        ElMessage.warning("请选择员工");
        return;
      }

      generating.value = true;
      try {
        // 模拟生成发展计划
        await new Promise((resolve) => setTimeout(resolve, 1000));

        developmentPlan.value = {
          trainingSuggestions: [
            "参加高级项目管理培训课程",
            "参与跨部门协作项目以提升人际交往能力",
            "学习数据分析和决策支持工具",
            "参加绩效领导力发展工作坊",
          ],
          promotionPath: [
            {
              position: "高级工程师",
              duration: "6-12个月",
              requirements: ["技术深度", "项目经验", "团队协作"],
            },
            {
              position: "技术专家",
              duration: "1-2年",
              requirements: ["专业认证", "技术创新", "知识分享"],
            },
            {
              position: "架构师",
              duration: "2-3年",
              requirements: ["系统设计", "技术规划", "跨团队协调"],
            },
          ],
          actionPlan: [
            {
              timestamp: "近期 (1-3个月)",
              type: "primary",
              content: "完成至少2个专业技术培训并获得认证",
            },
            {
              timestamp: "中期 (3-12个月)",
              type: "success",
              content: "主导一个跨部门技术项目并成功交付",
            },
            {
              timestamp: "长期 (1-2年)",
              type: "warning",
              content: "建立个人技术品牌，参与行业技术分享",
            },
          ],
        };
        setInterval(() => {
          onloadEcharts();
        }, 1000);

        ElMessage.success("发展计划生成成功");
      } catch (error) {
        // ElMessage.error("生成发展计划失败");
        console.log("生成发展计划失败", error);
      } finally {
        generating.value = false;
      }
    };

    const handleClickTAB = async () => {
      try {
        await api.getEmployeeData(employeeIdNow);
      } catch (error) {
        ElMessage.error("加载员工数据失败");
      }
    };

    onMounted(() => {
      loadData();
      isMounted = true; // 组件挂载时设为 true
      // onloadEcharts();
    });

    // 组件销毁前销毁图表实例
    onBeforeUnmount(() => {
      isMounted = false; // 组件卸载时设为 false
      if (myChart) {
        myChart.dispose(); // 关键：销毁实例
        myChart = null; // 解除引用
      }
    });

    const onloadEcharts = () => {
      // 先判断组件是否已卸载，已卸载则直接返回
      if (!isMounted) return;
      var chartDom = document.getElementById("main");
      myChart = echarts.init(chartDom);
      var option;

      option = {
        title: {
          text: "匹配结果展示",
        },
        legend: {
          data: ["实际能力", "岗位要求"],
        },
        radar: {
          // shape: 'circle',
          indicator: [
            { name: "学历", max: 6500 },
            { name: "工作经验", max: 16000 },
            { name: "培训考核", max: 30000 },
            { name: "绩效表现", max: 38000 },
            { name: "绩效领导力", max: 52000 },
            { name: "技术能力", max: 25000 },
          ],
        },
        series: [
          {
            name: "Budget vs spending",
            type: "radar",
            data: [
              {
                value: [4200, 3000, 20000, 35000, 50000, 18000],
                name: "实际能力",
              },
              {
                value: [5000, 14000, 28000, 26000, 42000, 21000],
                name: "岗位要求",
              },
            ],
          },
        ],
      };

      option && myChart.setOption(option);
    };

    const handleDownloadReport = () => {
      exportToPDF();
    };

    const exportToPDF = async () => {
      const element = document.getElementById("dev-content"); // 要导出的元素

      if (!element) {
        console.error("未找到要导出的元素");
        return;
      }

      try {
        // 使用 html2canvas 将元素转换为 canvas
        const canvas = await html2canvas(element, {
          scale: 8, // 提高分辨率
          useCORS: true, // 允许跨域图片
          logging: false, // 关闭日志
        });

        // 获取 canvas 的宽高
        const imgWidth = 220; // A4 纸的宽度 (mm)
        const pageHeight = 300; // A4 纸的高度 (mm)
        const imgHeight = (canvas.height * imgWidth) / canvas.width;

        // 创建 PDF
        const pdf = new jsPDF("p", "mm", "a4");

        let heightLeft = imgHeight;
        let position = 0;

        // 第一页
        pdf.addImage(canvas, "PNG", 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;

        // 如果内容超过一页，添加新页
        while (heightLeft >= 0) {
          position = heightLeft - imgHeight;
          pdf.addPage();
          pdf.addImage(canvas, "PNG", 0, position, imgWidth, imgHeight);
          heightLeft -= pageHeight;
        }

        // 保存 PDF
        pdf.save("员工能力评估与职业发展建议报告.pdf");
      } catch (error) {
        console.error("导出 PDF 失败:", error);
      }
    };

    return {
      developmentForm,
      selectedEmployee,
      developmentPlan,
      generating,
      employees,
      averageTrainingScore,
      averagePerformanceScore,
      workExperience,
      activeName,
      onEmployeeSelect,
      generateDevelopmentPlan,
      handleDownloadReport,
      handleClickTAB,
    };
  },
};
</script>

<style scoped>
.development-view {
  height: 100%;
}

.view-card {
  min-height: 600px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.development-content {
  padding: 20px 0;
}

.assessment-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.employee-overview {
  margin-bottom: 30px;
}

.metric-card {
  text-align: center;
  height: 120px;
}

.metric-content {
  padding: 20px;
}

.metric-value {
  font-size: 32px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 8px;
}

.metric-label {
  color: #909399;
  font-size: 14px;
}

.development-plan {
  margin-top: 30px;
}

.radar-chart-section {
  margin-bottom: 30px;
}

.radar-chart-placeholder {
  height: 300px;
  background: #f5f7fa;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 15px;
}

.suggestions-section {
  margin-bottom: 30px;
}

.suggestion-card {
  height: 100%;
}

.suggestion-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.suggestion-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.suggestion-item {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.suggestion-item:last-child {
  border-bottom: none;
}

.promotion-path {
  padding: 10px 0;
}

.path-step {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px dashed #e0e0e0;
}

.path-step:last-child {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.step-number {
  width: 30px;
  height: 30px;
  background: #409eff;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-weight: bold;
}

.step-content {
  flex: 1;
}

.step-title {
  font-weight: 600;
  margin-bottom: 5px;
}

.step-duration {
  color: #909399;
  font-size: 12px;
  margin-bottom: 8px;
}

.step-requirements {
  display: flex;
  gap: 5px;
  flex-wrap: wrap;
}

.action-plan-section {
  margin-top: 30px;
}

.empty-state {
  margin: 60px 0;
}
</style>
